define deploy::resources::war (
  $war_source = undef,
  $contexts   = {
    base       => $title,
    path       => $title,
    reloadable => false,
  },
  $version    = undef,
  $source     = 'http',
) {
  
  validate_hash($contexts)
  
  if !defined(Class['tomcat']) {
    include tomcat
  }
  
  $install_dir = $::tomcat::install_dir
  $sites_dir   = $::tomcat::sites_dir
  
  if $sites_dir == 'webapps'{
    $real_dir = "${install_dir}/tomcat/webapps"
  } else {
    $real_dir = $sites_dir
  }

  concat::fragment{ "server_xml_${title}":
    target  => "${install_dir}/tomcat/conf/server.xml",
    content => template('deploy/war.xml'),
    order   => "10-${name}",
  }
  
  if $version {
    $filename = "${title}-${version}.war"
  } else {
    $filename = "${title}.war"
  }

  if $war_source {
    $real_war_source = $war_source
  } else {
    $real_war_source = "puppet:///modules/deploy/${filename}"
  }

  case $source {
    'http': {
      staging::file { $filename:
        source => $real_war_source,
        target => "${real_dir}/${filename}",
        notify => Exec["clean_${real_dir}/${title}"],
      }
    }
    default: {
      fail('No war source specified')
    }
  }

  exec { "clean_${real_dir}/${title}":
    command     => "rm -rf ${title} && mkdir ${title} && unzip ${filename} -d ${title}/",
    cwd         => $real_dir,
    path        => '/usr/bin:/bin',
    user        => tomcat,
    group       => tomcat,
    logoutput   => on_failure,
    refreshonly => true,
    notify      => Class['tomcat::service'],
  }
  
}